﻿BINDING_HEADER_BINDING_AR = "AR Bindings"
BINDING_NAME_BINDING_N1 = "Rotation toggle"
BINDING_NAME_BINDING_N2 = "Interrupter toggle"

local TOOLTIP_TEXT1 = "Left-click to check the box"
local TOOLTIP_TEXT2 = "Right-click to config bindings"
local TOOLTIP_BINDING_LIST = "Currently bound: |cFFFFFFFF%s|r"
local LIST_SEPARATOR = "|r, |cFFFFFFFF"

local CAPTURE_TEXT = [[
Press a key to set binding.
Press |cFFFFFFFFESC|r to remove binding.]]

function BindingButton_OnLoad(self)
	local id = self:GetID()
	self.action = "BINDING_N"..id
	self:RegisterForClicks("LeftButtonUp", "RightButtonUp")
end

function BindingButton_OnClick(self, button)
	if button == "LeftButton" then
		local id = self:GetID()
		if id == 1 then	AR_Rotation_checkbox_OnClick()
		elseif id == 2 then AR_Interrupter_checkbox_OnClick()
		end
	elseif button == "RightButton" then
		BindingCaptureFrame.button = self
		BindingCaptureFrame:Show()
	end
end

function BindingButton_OnEnter(self)
	GameTooltip:SetOwner(self, "ANCHOR_BOTTOMRIGHT")
	GameTooltip:AddLine(TOOLTIP_TEXT1)
	GameTooltip:AddLine(TOOLTIP_TEXT2)
	local list = {GetBindingKey(self.action)}
	for i, key in ipairs(list) do
		list[i] = GetBindingText(key, "KEY_")
	end
	GameTooltip:AddLine(
	TOOLTIP_BINDING_LIST:format(table.concat(list, LIST_SEPARATOR)),
	NORMAL_FONT_COLOR.r,
	NORMAL_FONT_COLOR.g,
	NORMAL_FONT_COLOR.b,
	1
	)
	GameTooltip:Show()
end

function BindingButton_OnLeave(self)
	GameTooltip:Hide()
end

function BindingCapture_OnLoad(self)
	self:RegisterForClicks("AnyUp")
end

function BindingCapture_OnShow(self)
	self.text:SetText(CAPTURE_TEXT:format(self.button:GetID()))
end

function BindingCapture_OnKeyDown(self, key)
	if key == "ESCAPE" then
		local bindkey = GetBindingKey(self.button.action)
		if bindkey then
			SetBinding(bindkey, nil)
			SaveBindings(GetCurrentBindingSet())
		end
		self:Hide()
		return
	end
	local modifier = key:sub(2)
	if modifier == "SHIFT"
	or modifier == "CTRL"
	or modifier == "ALT"
	or key == "UNKNOWN" then
		return
	end
	print(GetBindingFromClick(key))
	if GetBindingFromClick(key) == "SCREENSHOT" then
		TakeScreenshot()
		return
	end
	if IsShiftKeyDown() then
		key = "SHIFT-"..key
	end
	if IsControlKeyDown() then
		key = "CTRL-"..key
	end
	if IsAltKeyDown() then
		key = "ALT-"..key
	end
	SetBinding(key, self.button.action)
	SaveBindings(GetCurrentBindingSet())
	self:Hide()
end

local buttonKeys = {
["MiddleButton"] = "BUTTON3",
["Button4"] = "BUTTON4",
["Button5"] = "BUTTON5"
}

function BindingCapture_OnClick(self, button)
	local key = buttonKeys[button]
	if not key then
		return
	end
	BindingCapture_OnKeyDown(self, key)
end